package com.heatup.apt.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import com.heatup.apt.common.constants.TemplateConstants;
import com.heatup.apt.model.weixin.Template;
import com.heatup.apt.model.weixin.TemplateParam;

import net.sf.json.JSONObject;

public final class TemplateMsgUtil {
	private final static String  template_sendmsg =String.valueOf(CommonPropertiesUtil.get("template_sendmsg")).trim();
	private final static String  template_gettoken =String.valueOf(CommonPropertiesUtil.get("template_gettoken")).trim();
	private final static String  template_appid =String.valueOf(CommonPropertiesUtil.get("template_appid")).trim();
	private final static String  template_secret =String.valueOf(CommonPropertiesUtil.get("template_secret"));

	public static boolean sendTemplateMsg(Template template,String token) {

		boolean flag = false;
	
		//String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
		String requestUrl=template_sendmsg;
		requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
		JSONObject jsonResult = TemplateMsgUtil.httpsRequestToJsonObject(requestUrl, "POST", template.toJSON());
		if (jsonResult != null) {
			int errorCode = jsonResult.getInt("errcode");
			String errorMessage = jsonResult.getString("errmsg");
			if (errorCode == 0) {
				flag = true;
			} else {
				System.out.println("============>>>模板消息发送失败:" + errorCode + "," + errorMessage +"template is :" +template.toJSON());
				flag = false;
			}
		}
		return flag;
	}

	/**
	 * 如果返回JSON数据包,转换为 JSONObject
	 * 
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @param needCert
	 * @return
	 */
	public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return jsonObject;
	}

	/**
	 * 
	 * @param requestUrl
	 *            接口地址
	 * @param requestMethod
	 *            请求方法：POST、GET...
	 * @param output
	 *            接口入参
	 * @param needCert
	 *            是否需要数字证书
	 * @return
	 */
	private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
			throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
			IOException, ProtocolException, UnsupportedEncodingException {

		URL url = new URL(requestUrl);
		HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches(false);
		connection.setRequestMethod(requestMethod);
		if (null != output) {
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(output.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = connection.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}

		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		connection.disconnect();
		return buffer;
	}
	
	/**
	 * 从微信平台获取token
	 * @return
	 */
	public static  String getAccessToken(){  
	        String requestUrl = template_gettoken;//"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	        String appid = template_appid;//"wx65db45e85c1be9c4";//第三方用户唯一凭证
	        String secret = template_secret ;//"3816ac8f220a3e9150fbab7321064d45";//    第三方用户唯一凭证密钥，即appsecret
	        requestUrl=requestUrl.replace("APPID", appid);  
	        requestUrl=requestUrl.replace("APPSECRET", secret);
	        JSONObject jsonObject= httpsRequestToJsonObject(requestUrl, "GET", null); 
	        String access_token = jsonObject.getString("access_token");
	    return access_token;
	      
	}
	
	
	public static void main(String args[]){
		/**
		Template tem=new Template();  
        tem.setTemplateId(TemplateConstants.USER_WAIT_SUCCESS_TIPS);
        tem.setTopColor("#333");  
        List<TemplateParam> paras=new ArrayList<TemplateParam>();  
        paras.add(new TemplateParam("first","您的排队订单已经成功预订！","#333"));  
        paras.add(new TemplateParam("keyword1","课程名称：团体课程","#333"));
        paras.add(new TemplateParam("keyword2","课程时间：2016-10-19","#333"));
        paras.add(new TemplateParam("remark","请及时处理,感谢你对云农批的支持!!!","#333"));  
                  
        tem.setTemplateParamList(paras);  
        tem.setToUser("oo2zXvyafJw01rcTs5s3m3V8x_x8");//用户openid
        //设置超链接
        tem.setUrl("");  
        //JSONObject jsonObject = JSONObject.fromObject(tem);
        String token ="mDg8SwdkyKawvtK9qmXd8pOQgeg4ho9CQWjlBf3CUE-Us0aLy-bGSvMV2QmppX5QDRS4dK73JRvsGa_SFNa32dFsfgPH5nMDTGNsPrqY5nkvHLJjevoD9Qcorm3gfZfbSBMbAFAXGR";
        //发送提醒
         //sendTemplateMsg(tem);
        sendTemplateMsg(tem, token);*/
		getAccessToken();
		
		
	}

}
